import 'package:flutter/material.dart';

class OverlayTestPage extends StatefulWidget {
  const OverlayTestPage({super.key});

  @override
  State<OverlayTestPage> createState() => _OverlayTestPageState();
}

class _OverlayTestPageState extends State<OverlayTestPage> {
  OverlayEntry? _overlayEntry;

  @override
  void initState() {
    super.initState();
    _overlayEntry = OverlayEntry(builder: (context) {
      return GestureDetector(
        onTap: () {
          // 点击蒙层时，移除蒙层
          _removeOverlay();
        },
        child: Material(
          color: Colors.transparent,
          child: Container(
            color: Colors.black.withOpacity(0.5),
            alignment: Alignment.center,
            child: IconButton(
              icon: const Icon(Icons.arrow_back),
              color: Colors.white,
              onPressed: () {
                // 点击返回按钮时，移除蒙层
                _removeOverlay();
              },
            ),
          ),
        ),
      );
    });
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // 在界面渲染完成后，添加蒙层
      Overlay.of(context).insert(_overlayEntry!);
    });
  }

  @override
  void dispose() {
    _overlayEntry = null;
    super.dispose();
  }

  void _removeOverlay() {
    _overlayEntry?.remove();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Custom Overlay'),
      ),
      body: Center(
        child: Column(
          children: [
            ElevatedButton(
              child: const Text('Show Overlay'),
              onPressed: () {
                // 点击按钮时，显示蒙层
                Overlay.of(context).insert(_overlayEntry!);
              },
            ),
            WillPopScope(
              onWillPop: () async {
                if (_overlayEntry!.mounted) {
                  _removeOverlay();
                  return false;
                }
                return true;
              },
              child: const SizedBox.shrink(),
            )
          ],
        ),
      ),
    );
  }
}